home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 16671 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  65 lines

  1. Path: dispatch.news.demon.net!demon!sianotts.demon.co.uk
  2. From: John Rawson <JR@sianotts.demon.co.uk>
  3. Newsgroups: comp.lang.c++
  4. Subject: 3d Array allocation
  5. Date: Thu, 11 Apr 1996 18:37:36 +0100
  6. Organization: None
  7. Message-ID: <316D4360.6446@sianotts.demon.co.uk>
  8. NNTP-Posting-Host: sianotts.demon.co.uk
  9. X-NNTP-Posting-Host: sianotts.demon.co.uk
  10. X-Mailer: Mozilla 2.0 (Win16; I)
  11. MIME-Version: 1.0
  12. Content-Type: text/plain; charset=us-ascii
  13. Content-Transfer-Encoding: 7bit
  14.  
  15. Hello group.
  16.  
  17. I'm very new to c++ and have just wrote a function to allocate a 3d array
  18. of char's it compiles and seems to work OK,I'm just worried that if the
  19. memory allocation fails then I'm deleting everything correctly ready to
  20. try again.All criticisms/improvements would be appreciated.Many thanks.
  21.  
  22. here's the function...
  23.  
  24. char ***New_3D_Char_Array(int n1,int n2,int n3)
  25. {
  26. int i,j,k;
  27. char ***Array_Pointer=new char **[n1];
  28. if (!Array_Pointer)
  29.     return NULL;//serious lack of memory!!!
  30. for (i=0;i<n1;i++)
  31.     {
  32.     Array_Pointer[i]=new char *[n2];
  33.     if (!Array_Pointer[i])//check for allocation failure
  34.         {
  35.         //delete what we've allocated up to yet
  36.         for (k=0;k<i;k++)
  37.             delete[] Array_Pointer[k];
  38.         delete [] Array_Pointer;
  39.         return NULL;
  40.         }
  41.     }
  42. for (i=0;i<n1;i++)
  43.     for (j=0;j<n2;j++)
  44.     {
  45.     Array_Pointer[i][j]=new char[n3];
  46.     if (!Array_Pointer[i][j])//check again for failure
  47.         {
  48.         //again,delete what's already gone
  49.         //first what we've done in the current j loop
  50.         for (k=0;k<j;k++)
  51.             delete [] Array_Pointer[i][k];
  52.         //and then then the other i & j loops
  53.         for (k=0;k<i;k++)
  54.             {
  55.             for (j=0;j<n2;j++)
  56.                 delete[] Array_Pointer[k][j];
  57.             delete [] Array_Pointer[k];
  58.             }
  59.         delete [] Array_Pointer;
  60.         return NULL;
  61.         }
  62.     }
  63. return Array_Pointer;
  64. }
  65.